package com.qk.management.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qk.common.PageResult;
import com.qk.common.constant.BusinessStatusConstants;
import com.qk.common.constant.ClueStatusConstants;
import com.qk.common.constant.ClueTrackRecordStatus;
import com.qk.common.enums.ParamEnum;
import com.qk.common.exception.CommonException;
import com.qk.common.util.CurrentUserContextHolders;
import com.qk.domain.clue.ClueDO;
import com.qk.domain.clue.CluePoolDTO;
import com.qk.dto.clue.ClueDTO;
import com.qk.dto.clue.ClueListDTO;
import com.qk.dto.clue.MarkFalseClueDTO;
import com.qk.dto.clue.UpdateClueInfoDTO;
import com.qk.entity.Business;
import com.qk.entity.Clue;
import com.qk.entity.ClueTrackRecord;
import com.qk.entity.User;
import com.qk.management.mapper.BusinessMapper;
import com.qk.management.mapper.ClueMapper;
import com.qk.management.mapper.ClueTrackRecordMapper;
import com.qk.management.mapper.UserMapper;
import com.qk.management.service.ClueService;
import com.qk.vo.clue.CluePoolVO;
import com.qk.vo.clue.ClueVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;


/**
 * @author: Enid
 * @date: 2025/10/13 16:56
 * @description:
 */
@Slf4j
@Service
public class ClueServiceImpl extends ServiceImpl<ClueMapper, Clue> implements ClueService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ClueTrackRecordMapper clueTrackRecordMapper;
    @Autowired
    private BusinessMapper businessMapper;
    @Autowired
    private ClueMapper clueMapper;

    @Override
    public PageResult<CluePoolVO> poolList(CluePoolDTO dto) {
        PageHelper.startPage(dto.getPage(),dto.getPageSize());
        List<CluePoolVO> list = clueMapper.selectPoolList(dto);
        Page<CluePoolVO> page = (Page<CluePoolVO>) list;
        return PageResult.<CluePoolVO>builder()
                .rows(page.getResult())
                .total(Long.valueOf(page.getTotal()).intValue())
                .build();
    }

    @Override
    public void toFake(Integer id,MarkFalseClueDTO dto) {
        //根据ID更新线索的状态为 4
        clueMapper.update(Wrappers.<Clue>lambdaUpdate()
                .eq(Clue::getId,id)
                .set(Clue::getStatus,ClueStatusConstants.FALSE_CLUE)
                .set(Clue::getNextTime,null)
                .set(Clue::getSubject,null)
                .set(Clue::getUpdateTime,LocalDateTime.now())
        );
        //添加一条跟进记录，跟进的类型type为0，表示伪线索
        Clue clue = clueMapper.selectById(id);
        ClueTrackRecord record = BeanUtil.copyProperties(clue,ClueTrackRecord.class);
        record.setId(null);
        record.setClueId(clue.getId());
        record.setRecord(dto.getRemark());
        record.setNextTime(null);
        record.setType(0);
        record.setFalseReason(dto.getReason());
        record.setCreateTime(LocalDateTime.now());
        clueTrackRecordMapper.insert(record);
    }


    @Transactional
    @Override
    public void toBusiness(Integer id) {
        //1、根据id获取线索信息
        Clue clue = this.getById(id);
        clue.setStatus(ClueStatusConstants.TO_BUSINESS);
        clue.setUpdateTime(LocalDateTime.now());
        this.updateById(clue);
        Business business = BeanUtil.copyProperties(clue, Business.class);
        business.setId(null);
        business.setCreateTime(LocalDateTime.now());
        business.setUpdateTime(LocalDateTime.now());
        business.setNextTime(null);
        business.setUserId(null);
        business.setStatus(BusinessStatusConstants.WAIT_ALLOCATION);
        business.setClueId(id);
        businessMapper.insert(business);

    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateClueInfoById(UpdateClueInfoDTO dto) {

        Clue clue = BeanUtil.copyProperties(dto, Clue.class);
        clue.setUpdateTime(LocalDateTime.now());
        if (Objects.equals(dto.getStatus(), ClueStatusConstants.WAIT_ALLOCATION)){
            clue.setStatus(ClueStatusConstants.FOLLOW_UP);
        }
        this.baseMapper.updateById(clue);


        ClueTrackRecord clueTrackRecord = BeanUtil.copyProperties(dto, ClueTrackRecord.class);

        clueTrackRecord.setCreateTime(LocalDateTime.now());
        clueTrackRecord.setId(null);
        clueTrackRecord.setClueId(clue.getId());
        clueTrackRecord.setType(ClueTrackRecordStatus.NORMAL_FOLLOW_UP);
         clueTrackRecord.setUserId(CurrentUserContextHolders.get());
        clueTrackRecordMapper.insert(clueTrackRecord);
    }


    /**
     * 获取线索详情
     * @param id 线索id
     * @return ClueVO
     */
    @Override
    public ClueVO getClueInfoById(Integer id) {
        Clue  clue= this.baseMapper.selectById(id);
        Integer userId = clue.getUserId();
        User user = userMapper.selectById(userId);
        List<ClueTrackRecord> clueTrackRecords=clueTrackRecordMapper.selectList(Wrappers.lambdaQuery(ClueTrackRecord.class)
                .in(ClueTrackRecord::getClueId,id)
        );
        ClueVO clueVO = BeanUtil.copyProperties(clue, ClueVO.class);
        List<ClueVO.ClueTrackRecordVO> list=clueTrackRecords.stream().map(item->{
            return BeanUtil.copyProperties(item, ClueVO.ClueTrackRecordVO.class);
        }).toList();
        clueVO.setTrackRecords(list);
        return clueVO;
    }


    @Override
    public PageResult<ClueDO> cluesList(ClueListDTO clueListDTO) {
        PageHelper.startPage(clueListDTO.getPage(),clueListDTO.getPageSize());
        Page<ClueDO> list =(Page<ClueDO>) this.baseMapper.selectByPage(clueListDTO);
        return PageResult.<ClueDO>builder()
                .rows(list.getResult())
                .total(Long.valueOf(list.getTotal()).intValue())
                .build();
    }


    @Override
    public void addClue(ClueDTO clueDTO) {
        if (ObjectUtil.isEmpty(clueDTO.getPhone()) || ObjectUtil.isEmpty(clueDTO.getChannel())){
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        Clue clue = BeanUtil.copyProperties(clueDTO, Clue.class);
        clue.setStatus(ClueStatusConstants.WAIT_ALLOCATION);
        clue.setCreateTime(LocalDateTime.now());
        clue.setUpdateTime(LocalDateTime.now());
        this.save(clue);
    }
}
